#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
快速代理测试脚本
简化版本，用于快速验证代理可用性
"""

import requests
import time

def test_proxy_quick(proxy_url, proxy_name="测试代理"):
    """快速测试代理"""
    print(f"\n{'='*50}")
    print(f"测试: {proxy_name}")
    print(f"地址: {proxy_url or '无代理'}")
    print(f"{'='*50}")
    
    if not proxy_url:
        proxies = None
        print("🔍 无代理模式测试...")
    else:
        proxies = {
            'http': proxy_url,
            'https': proxy_url
        }
        print(f"🔍 代理模式测试: {proxy_url}")
    
    # 测试URL列表
    test_urls = [
        ('IP检查', 'http://httpbin.org/ip'),
        ('百度', 'http://www.baidu.com'),
        ('ScienceDirect', 'https://www.sciencedirect.com')
    ]
    
    results = []
    
    for name, url in test_urls:
        print(f"\n📡 测试 {name}...")
        start_time = time.time()
        
        try:
            response = requests.get(
                url, 
                proxies=proxies, 
                timeout=10,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                }
            )
            
            response_time = time.time() - start_time
            
            if response.status_code == 200:
                print(f"✅ {name}: 成功 (状态码: {response.status_code}, 耗时: {response_time:.2f}s)")
                
                # 特殊处理IP检查
                if 'httpbin.org/ip' in url:
                    try:
                        ip_info = response.json()
                        ip = ip_info.get('origin', 'Unknown')
                        print(f"   📍 检测到IP: {ip}")
                    except:
                        print(f"   ⚠️  无法解析IP信息")
                
                results.append(True)
            else:
                print(f"⚠️  {name}: 响应异常 (状态码: {response.status_code})")
                results.append(False)
                
        except requests.exceptions.Timeout:
            print(f"❌ {name}: 连接超时")
            results.append(False)
        except requests.exceptions.ConnectionError as e:
            print(f"❌ {name}: 连接错误 - {str(e)}")
            results.append(False)
        except Exception as e:
            print(f"❌ {name}: 其他错误 - {str(e)}")
            results.append(False)
    
    # 总结
    success_count = sum(results)
    total_count = len(results)
    success_rate = (success_count / total_count) * 100
    
    print(f"\n📊 测试结果:")
    print(f"   成功: {success_count}/{total_count} ({success_rate:.1f}%)")
    
    if success_rate >= 80:
        print(f"🎉 代理状态: 优秀")
        return "excellent"
    elif success_rate >= 50:
        print(f"👍 代理状态: 可用")
        return "good"
    elif success_rate > 0:
        print(f"⚠️  代理状态: 部分可用")
        return "partial"
    else:
        print(f"❌ 代理状态: 不可用")
        return "failed"

def main():
    """主函数"""
    print("🚀 快速代理测试工具")
    print("="*60)
    
    # 预设代理列表
    test_proxies = [
        ("无代理模式", None),
        ("代理1", "http://120.92.212.16:7890"),
        # 可以添加更多代理
    ]
    
    print("选择测试模式:")
    print("1. 测试所有预设代理")
    print("2. 测试单个代理")
    print("3. 只测试无代理模式")
    
    try:
        choice = input("\n请输入选择 (1-3): ").strip()
        
        if choice == '1':
            print("\n🔄 开始测试所有预设代理...")
            results = []
            for name, proxy_url in test_proxies:
                result = test_proxy_quick(proxy_url, name)
                results.append((name, result))
            
            print(f"\n{'='*60}")
            print("📋 最终报告:")
            print(f"{'='*60}")
            for name, status in results:
                status_emoji = {
                    'excellent': '🎉',
                    'good': '👍',
                    'partial': '⚠️',
                    'failed': '❌'
                }.get(status, '❓')
                print(f"{status_emoji} {name}: {status}")
                
        elif choice == '2':
            proxy_url = input("请输入代理地址 (格式: http://ip:port): ").strip()
            if proxy_url:
                test_proxy_quick(proxy_url, "用户输入代理")
            else:
                print("❌ 代理地址不能为空")
                
        elif choice == '3':
            test_proxy_quick(None, "无代理模式")
            
        else:
            print("❌ 无效选择")
            
    except KeyboardInterrupt:
        print("\n\n⏹️  测试被用户中断")
    except Exception as e:
        print(f"\n❌ 发生错误: {e}")

if __name__ == "__main__":
    main()